package com.servlet.log;

import com.service.AdminService;
import com.service.EmployeeService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证
 * @author huawei
 *
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //1.获取用户名和密码
        String admin=req.getParameter("admin");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        //2.检查用户名和密码正确性
        if (admin!=null&&admin.equals("Admin")){
            AdminService adminService=new AdminService();
            boolean log=adminService.checkLogin(userName,password);

            if (log) {
                HttpSession session = req.getSession();
                session.setAttribute("adminName", userName);
                session.setAttribute("userName", userName);
                resp.sendRedirect("admin/adminmain.jsp" );
            } else {
                req.setAttribute("userName",userName);
                req.setAttribute("errorMessage", "登录失败，请重新登录");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        }else {
            EmployeeService employeeService=new EmployeeService();
            boolean log=employeeService.checkLogin(userName,password);

            if (log) {
                HttpSession session = req.getSession();
                session.setAttribute("userName", userName);
                resp.sendRedirect("user/usermain.jsp" );
            } else {
                req.setAttribute("userName", userName);
                req.setAttribute("errorMessage", "登录失败，请重新登录");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        }

    }
}
